﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace Netcare.Core
{
    public class App
    {
        public static void InitializeAppDomainAndLogger(string hash = null)
        {
            if (hash == null)
                hash = String.Empty;
            AppDomain.CurrentDomain.SetData(".appHash", hash);

            Log.Listeners.Clear();
            Log.Listeners.Add(new ConsoleLogListener());
            Log.Listeners.Add(new TextWriterLogListener(CreateLogger()));

            SetRunningDirectory();
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }


        private static void SetRunningDirectory()
        {
            var asm = Assembly.GetEntryAssembly();
            if (asm != null)
            {
                var dir = Path.GetDirectoryName(asm.Location);
                Directory.SetCurrentDirectory(dir);
            }
        }


        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Log.WriteException(e.ExceptionObject as Exception,
                "Unhandled exception occurred{0}", e.IsTerminating ? ", application is shutting down!" : String.Empty);
        }


        private static string CreateLogger()
        {
            string logDirFormat = null;
            string logPathFormat = null;
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                logDirFormat = @"{0}\ChinaTelecom\Netcare\Logs";
                logPathFormat = @"{0}\ChinaTelecom\Netcare\Logs\{1}{2}.log";
            }
            else if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                logDirFormat = "{0}/china-telecom/netcare/logs";
                logPathFormat = "{0}/china-telecom/netcare/logs/{1}{2}.log";
            }

            var dir = String.Format(logDirFormat,
                Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            var log = String.Format(logPathFormat,
                Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                DateTime.Today.ToString("yyyy-MM-dd"),
                AppDomain.CurrentDomain.GetData(".appHash").ToString());

            // for windows, it should return something like
            //  C:\ProgramData\ChinaTelecom\Netcare\Logs\xxx.log
            // while for linux, it should return something like
            //  /usr/share/china-telecom/netcare/logs/xxx.log
            return log;
        }
    }
}
